import mongoose from "mongoose";
import utils from "../utils";
import { isEmail, isPhone } from "../config";
const moment = require("moment");

export interface IPhoneCode extends mongoose.Document {
  code: string;
  phone: string;
  createTime: string;
  expireTime: string;
}

export const model = {
  code: String,
  phone: String,
  createTime: String,
  expireTime: String,
};

export const Schema = new mongoose.Schema(model);

const m: any = mongoose.model<IPhoneCode>("PhoneCode", Schema);

m.hasExpired = async function(phone: string, phoneCode: string) {
  const { createTime, expireTime } = await m.findOne({ phone, code: phoneCode });
  const now = moment().unix();
  if (now > expireTime) {
    return true;
  }
  return false;
};

m.hasPhoneCode = async function(phoneCode: string, phone: string) {
  const res = await m.findOne({ phoneCode, phone });
  let ret = true;
  if (!res) {
    ret = false;
  }
  return ret;
};

m.delPhoneCode = async function(phoneCode: string, phone: string) {
  const res = await m.deleteOne({ code: phoneCode, phone });
  if (res.n) {
    return true;
  }
  return false;
};

m.validatePhoneCode = async function(phoneCode: string, phone: string) {
  const res = await m.findOne({ code: phoneCode, phone });
  if (m.hasPhoneCode(phoneCode, phone)) {
    if (res && res.code == phoneCode) {
      return true;
    }
    return false;
  }
  return false;
};

export default m;
